package com.yqg.protection.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yqg.protection.entity.Organization;
import com.yqg.protection.mapper.OrganizationMapper;
import com.yqg.protection.service.IOrganizationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;

/**
 * OrganizationServiceImpl 服务实现类
 * @author zxf
 * @since 2024-01-01
 */
@Service
@Slf4j
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements IOrganizationService {

    @Autowired
    private OrganizationMapper organizationMapper;

    @Override
    public void export(HttpServletResponse response) {
        try {
            //设置下载
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = null;
            fileName = URLEncoder.encode("组织信息表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            //查询用户所有数据
            QueryWrapper<Organization> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("is_delete", "0");
            List<Organization> exportData = organizationMapper.selectList(queryWrapper);
            //EasyExcel 写操作
            EasyExcel.write(response.getOutputStream(), Organization.class)
                    .sheet("组织信息表")
                    .doWrite(exportData);
        } catch (Exception e) {
            log.info("exception ", e);
        }
    }
}
